package com.xdy.mdc.adapter;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.xdy.mdc.databinding.ItemComponentBinding;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: XDY.
 * @Email: 2280944114@qq.com
 * @CreateTime: 2023-08-27  21:35
 * @Description: 主界面适配器
 * @Version: 1.0
 */
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {

    private List<String> data = new ArrayList<>();

    @NonNull
    @Override
    public MainAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemComponentBinding binding = ItemComponentBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull MainAdapter.ViewHolder holder, int position) {
        holder.bind(getData(position));
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public String getData(int position) {
        return data.get(position);
    }

    public void setDatum(List<String> datum) {
        if (datum != null && datum.size() > 0){
            this.data.clear();
            this.data.addAll(datum);
            //通知数据发生了变化
            notifyDataSetChanged();
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private final ItemComponentBinding binding;

        public ViewHolder(@NonNull ItemComponentBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        public void bind(String data){
            binding.item.setText(data);
            binding.item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        Intent intent = new Intent();
                        String className = "com.xdy.mdc.activity.".concat(data).concat("Activity");
                        intent.setClass(v.getContext(),Class.forName(className));
                        binding.item.getContext().startActivity(intent);
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
}